const router = require('express').Router();
const {DB} = require('../database/index');
const jwt = require('jsonwebtoken');
const privateKey = 'golf'
const {iot} = require('../lot')
// 实时状态模型
const Model = {
    temperature: '10',
    humidity: '20',
    windSpeed: '3',
    light: '100',
    nitrogen: '3.2',
    switch: '1',
// 阈值
    maxTemperature: '50',
    minHumidity: '10'
}


// 保存当前模型状态
const saveRecord = async () => {
    await DB.Record.create(Model)
    return
}
router.get('/sync', async (req, res) => {
    await DB.init()
    res.send('数据库初始化成功')
})
// 获取模型状态
router.get('/model', async (req, res) => {
    res.json({
        code: 200,
        message: '获取模型状态成功',
        data: Model
    })
})
// 查询列表数据
router.get('/list', async (req, res) => {
    const list = await DB.Record.findAll()
    res.json({
        code: 200,
        message: '查询成功',
        data: list
    })
})

// 保存数据
router.post('/save', async (req, res) => {
    const data = req.body
    // 同步服务器数据模型
    Object.keys(Model).forEach(key => {
        if (data[key] === null || data[key] === undefined) return
        Model[key] = data[key]
    })
    if (Model.humidity < Model.minHumidity) {
        Model.switch = '1'
        await DB.Log.create({
            desc: '湿度过低，已自动打开喷水装置'
        })
    }
    if (Model.temperature > Model.maxTemperature) {
        Model.switch = '1'
        await DB.Log.create({
            desc: '温度过高，已自动打开喷水装置'
        })
    }
    DB.Record.create(data).then(result => {
        res.json({
            code: 200,
            message: '保存成功',
        })
    })
})

// 切换开关
router.post('/switch', async (req, res) => {
    Model.switch = req.body.switch
    await DB.Log.create({
        desc: `喷水装置已手动${Model.switch ? '开启' : '关闭'}了`
    })
    await saveRecord()
    res.json({
        code: 200,
        message: `喷水装置已${Model.switch ? '开启' : '关闭'}`
    })
})

// 获取动态图
router.get('/log', async (req, res) => {
    const data = await DB.Log.findAll()
    res.json({
        code: 200,
        message: '查询成功',
        data,
    })
})

// 设定阈值
router.post('/set', async (req, res) => {
    const {maxTemperature, minHumidity} = req.body
    // Model.maxTemperature = maxTemperature;
    // Model.minHumidity = minHumidity;
    await DB.Log.create({
        desc: `阈值已手动设定 温度：${maxTemperature}℃ 湿度：${minHumidity}%RH`
    })
    res.json({
        code: 200,
        message: '设定成功'
    })
})

// 登录
router.post('/login', async (req, res) => {
    const {username, password} = req.body
    const user = await DB.User.findOne({
        where: {
            username,
            password
        }
    })
    if (!user) {
        res.json({
            code: 500,
            message: '账号或密码错误'
        })
        return
    }
    res.json({
        code: 200,
        message: '登陆成功',
        token: jwt.sign({id: user.id}, privateKey)
    })
})

// 注册
router.post('/reg', async (req, res) => {
    const {username, password} = req.body
    const data = await DB.User.findOne({
        where: {
            username,
        }
    })
    if (data) {

        res.json({
            code: 500,
            message: '注册失败，账户已存在'
        })
        return
    }
    await DB.User.create({
        username,
        password,
    })
    res.json({
        code: 200,
        message: '注册成功'
    })
})

// 查询阿里云设备列表

router.get('/iot/list', async (req, res) => {
    const data = await iot('QueryDevice').then(res => {
        return res?.Data?.DeviceInfo || []
    })
    res.json(data)
})

router.post('/iot/add', async (req, res) => {
    const params = req.body
    iot('RegisterDevice', params).then(_ => {
        res.json({params, message: '设备添加成功',code:200})
    }).catch(err => {
        res.json({code: 500, message: '添加设备失败,请检查设备名称是否重复', err})
    })
})
// 删除设备
router.post('/iot/del', async (req, res) => {
    const params = req.body
   iot('DeleteDevice', params).then(_=>{
       res.json({
           code: 200,
           message: '设备删除成功！'
       })
   }).catch(err=>{
       res.json({
           code:500,
           message:'删除失败',
           err
       })
   })

})
router.post('/iot/edit',async(req,res)=>{
    const params = req.body
    iot('DeleteDevice', params).then(_=>{
        iot('RegisterDevice', params).then(_ => {
            res.json({params, message: '修改成功',code:200})
        }).catch(err => {
            res.json({code: 500, message: '添加失败,请检查设备名称是否重复', err})
        })
    }).catch(err=>{
        res.json({code: 500, message: '添加失败,请检查设备名称是否重复', err})
    })
})
// 修改设备

router.post('/iot/switch', async (req, res) => {
    const params = req.body;
    const action = params.DeviceStatus === 'DISABLE' ? 'EnableThing' : 'DisableThing'
   iot(action,params).then(_=>{
       res.json({
           code:200,
           message:'操作成功'
       })
   }).catch(err=>{
       res.json({
           code:500,
           message:'操作失败'
       })
   })
})
module.exports = router